package cn.fingersoft.im.glide

import android.util.Log
import cn.fingersoft.util.BuildConfigUtil
import okhttp3.OkHttpClient
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * @author liubinbin
 */
class UnsafeOkHttpClient {
    /**
     * 禁止解析Manifest文件
     * 主要针对V3升级到v4的用户，可以提升初始化速度，避免一些潜在错误
     *
     * @return
     */
    val isManifestParsingEnabled: Boolean
        get() = false

    companion object {
        // Create a trust manager that does not validate certificate chains
        @JvmStatic
        val unsafeOkHttpClient:

        // Install the all-trusting trust manager

        // Create an ssl socket factory with our all-trusting manager
            OkHttpClient
            get() = try {
                // Create a trust manager that does not validate certificate chains
                val trustAllCerts = arrayOf<TrustManager>(
                    object : X509TrustManager {
                        @Throws(CertificateException::class)
                        override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
                        }

                        @Throws(CertificateException::class)
                        override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
                        }

                        override fun getAcceptedIssuers(): Array<X509Certificate> {
                            return arrayOf()
                        }
                    }
                )

                // Install the all-trusting trust manager
                val sslContext = SSLContext.getInstance("SSL")
                sslContext.init(null, trustAllCerts, SecureRandom())

                // Create an ssl socket factory with our all-trusting manager
                val sslSocketFactory = sslContext.socketFactory
                val builder = OkHttpClient.Builder()
                builder.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
                builder.hostnameVerifier { hostname, session ->
                    if (BuildConfigUtil.getBoolean("useSSLTrustManager", false)) {
                        HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session)
                    } else {
                        true
                    }
                }
                builder.connectTimeout(20, TimeUnit.SECONDS)
                builder.readTimeout(20, TimeUnit.SECONDS)
                builder.writeTimeout(20, TimeUnit.SECONDS)
                builder.build()
            } catch (e: Exception) {
                throw RuntimeException(e)
            }
    }
}
